package cn.platform.service.impl;

import cn.platform.entity.Clazz1;
import cn.platform.entity.StuRecord;
import cn.platform.entity.Student;
import cn.platform.entity.Teacher;
import cn.platform.mapper.*;
import cn.platform.request.StuRecord.StuRecordQueryDTO;
import cn.platform.request.StuRecord.StuRecordUpdateDTO;
import cn.platform.response.PageResult;
import cn.platform.response.StuRecordVO;
import cn.platform.service.StuRecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Year;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j

public class StuRecordServiceImpl implements StuRecordService {

    @Autowired
    private StuRecordMapper stuRecordMapper;

    @Autowired
    private ClazzMapper1 clazzMapper1;

    @Autowired
    private TeacherMapper1 teacherMapper1;

    @Autowired
    private StudentMapper1 studentMapper1;



    // 新增：获取学生列表
    public List<Map<String, Object>> getStudents(String name) {
        List<Student> students;
        if (name != null && !name.isEmpty()) {
            students = studentMapper1.searchByName(name);
        } else {
            students = studentMapper1.getAll();//后续实现
        }
        return students.stream()
                .map(s -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", s.getId());
                    map.put("name", s.getRealName());
                    return map;
                })
                .collect(Collectors.toList());
    }

    // 新增：获取老师列表
    public List<Map<String, Object>> getTeachers(String name) {
        List<Teacher> teachers;
        if (name != null && !name.isEmpty()) {
            teachers = teacherMapper1.searchByName(name);//后续实现
        } else {
            teachers = teacherMapper1.getAll();//后续实现
        }
        return teachers.stream()
                .map(t -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", t.getId());
                    map.put("name", t.getRealName());
                    return map;
                })
                .collect(Collectors.toList());
    }


    public PageResult<StuRecordVO> page(StuRecordQueryDTO queryDTO) {
        // 处理年级转换逻辑
        if (queryDTO.getGrade() != null && queryDTO.getGrade() > 0) {
            int currentYear = Year.now().getValue();
            queryDTO.setGradeYear(currentYear - queryDTO.getGrade() + 1);
        }

        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());

        Map<String, Object> map = new HashMap<>();
        map.put("title", queryDTO.getTitle());
        map.put("publisher", queryDTO.getPublisher());
        map.put("gradeYear", queryDTO.getGradeYear());
        map.put("classNum", queryDTO.getClassNum());
        map.put("studentName", queryDTO.getStudentName());
        map.put("type", queryDTO.getType());

        // 处理时间范围
        if (queryDTO.getStartTime() != null) {
            map.put("startTime", LocalDateTime.of(queryDTO.getStartTime(), LocalTime.MIN));
        }
        if (queryDTO.getEndTime() != null) {
            map.put("endTime", LocalDateTime.of(queryDTO.getEndTime(), LocalTime.MAX));
        }

        Page<StuRecordVO> page = stuRecordMapper.pageQuery(map);

        // 转换年级显示格式
        int currentYear = Year.now().getValue();
        for (StuRecordVO vo : page.getResult()) {
            if (vo.getGradeYear() != null) {
                vo.setGrade(currentYear - vo.getGradeYear() + 1);
            }
        }

        return new PageResult<>(page.getTotal(), page.getResult());
    }



    @Override
    public StuRecordVO detail(Integer id) {
        StuRecord stuRecord = stuRecordMapper.getById(id);

        // 获取关联数据
        String publisher = teacherMapper1.getNameById(stuRecord.getPubId());
        String studentName = studentMapper1.getNameById(stuRecord.getStudentId());

        // 获取班级信息
        Integer classNum = null;
        Integer gradeYear = null;
        if (stuRecord.getStudentId() != null) {
            Student student = studentMapper1.getById(stuRecord.getStudentId());
            if (student.getClassID() != null) {
                Clazz1 clazz1 = clazzMapper1.getById(student.getClassID());
                classNum = clazz1.getClassNum();
                gradeYear = clazz1.getGradeYear();
            }
        }

        // 计算当前年级
        Integer grade = null;
        if (gradeYear != null) {
            int currentYear = Year.now().getValue();
            grade = currentYear - gradeYear + 1;
            if (grade > 6) grade = null; // 超过六年级标记为已毕业
        }

        // 构建VO对象
        StuRecordVO vo = new StuRecordVO();
        BeanUtils.copyProperties(stuRecord, vo);
        vo.setPublisher(publisher);
        vo.setStudentName(studentName);
        vo.setClassNum(classNum);
        vo.setGrade(grade);  // 设置计算后的年级
        vo.setGradeYear(gradeYear); // 保留原始入学年份

        // 关联老师，获取发布人姓名，用于下拉列表数据展示
        if (stuRecord.getPubId() != null) {
            Teacher teacher = teacherMapper1.getById(stuRecord.getPubId());
            if (teacher != null) {
                vo.setPublisher(teacher.getRealName());
            }
        }


        return vo;
    }



    @Transactional
    public void update(StuRecordUpdateDTO dto) {
        StuRecord stuRecord = stuRecordMapper.getupdateById(dto.getId());//后续实现
        if (stuRecord == null) {
            throw new RuntimeException("成绩不存在");
        }
        // 只更新允许修改的字段
        stuRecord.setTitle(dto.getTitle());
        stuRecord.setContent(dto.getContent());
        stuRecord.setUpdateTime(LocalDateTime.now());
        stuRecordMapper.updateStuRecord(stuRecord);//后续实现
    }


    @Override
    public void save(StuRecord stuRecord) {
        stuRecord.setPubTime(LocalDateTime.now());
        stuRecord.setUpdateTime(LocalDateTime.now());
        stuRecordMapper.insertStuRecord(stuRecord);
    }





    @Override
    public void delete(Integer id) {
        stuRecordMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        stuRecordMapper.deleteBatch(ids);
    }


}
